package nbn.android.myyoutubeclient.parse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URI;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class Parser {
	static String tag="Parser";
	
	
	private static final String ATR_THUMB_URL = "url";
	
	public NodeList getResponceNodeList(String service_url) {
		String searchResponce = getHttpResponse(URI.create(service_url));
		//Log.i("url",""+service_url);
//		Log.i(tag,""+searchResponce);
		Document doc;
		NodeList items = null;
		if (searchResponce != null) {
//			Log.i(tag,"executed");
			try {
				doc = getDomElement(searchResponce);
				items = doc.getElementsByTagName("entry");				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return items;
	}
	

	public NodeList getResponceElement(String service_url) {
		String searchResponce = getHttpResponse(URI.create(service_url));

		Document doc;
		NodeList items = null;
		if (searchResponce != null) {
			try {
				doc = getDomElement(searchResponce);
				items = doc.getElementsByTagName("entry");				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return items;
	}
	
	public static String getHttpResponse(URI uri) {
//	    Log.d(tag, "Going to make a get request");
	    StringBuilder response = new StringBuilder();
	    try {
	        HttpGet get = new HttpGet();
	        get.setURI(uri);
	        DefaultHttpClient httpClient = new DefaultHttpClient();
	        HttpResponse httpResponse = httpClient.execute(get);
	        if (httpResponse.getStatusLine().getStatusCode() == 200) {
//	            Log.d(tag, "HTTP Get succeeded");

	            HttpEntity messageEntity = httpResponse.getEntity();
	            InputStream is = messageEntity.getContent();
	            BufferedReader br = new BufferedReader(new InputStreamReader(is));
	            String line;
	            while ((line = br.readLine()) != null) {
	                response.append(line);
	            }
	        }
	    } catch (Exception e) {
	        Log.e(tag, e.getMessage());
	    }
//	    Log.d(tag, "Done with HTTP getting");
	    return response.toString();
	}
	
	public static Document getDomElement(String xml) {
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			doc = (Document) db.parse(is);

		} catch (ParserConfigurationException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (SAXException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		}

		return doc;
	}
	public static String getImageUrlAttributeValue(String tag,String attribute_key,String attribute_value,Element e){
		NodeList list=e.getElementsByTagName(tag);
		String url=null;
		for(int i=0;i<list.getLength();i++){
			Element element=(Element)list.item(i);
			if(element.getAttribute(attribute_key).equals(attribute_value)){
				url=element.getAttribute(ATR_THUMB_URL);
				return url;
			}
		}
		return url;
	}
	
	public static String getImageUrlAttributeValue(String tag,Element e){
		NodeList list=e.getElementsByTagName(tag);
		String url=null;
		for(int i=0;i<list.getLength();i++){
			Element element=(Element)list.item(i);
				url=element.getAttribute(ATR_THUMB_URL);
				return url;
		}
		return url;
	}
	public static String getAttributeValue(Element e,String tag,String attribute){
		String atr=null;
		NodeList list=e.getElementsByTagName(tag);
		Element element=(Element)list.item(0);
		if(element!=null)
			atr=element.getAttribute(attribute);
		else atr="";
		return atr;
	}
	
	public static String getValue(Element item, String str) {
		NodeList n = item.getElementsByTagName(str);
		return getElementValue(n.item(0));
	}
	
	public static final String getElementValue(Node elem) {
		Node child;
		if (elem != null) {
			if (elem.hasChildNodes()) {
				for (child = elem.getFirstChild(); child != null; child = child
						.getNextSibling()) {
					if (child.getNodeType() == Node.TEXT_NODE
							|| (child.getNodeType() == Node.CDATA_SECTION_NODE)) {
						return child.getNodeValue();
					}
				}
			}
		}
		return "";
	}
}
